package com.lsz.custom2.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.lsz.custom2.DTBrowser;
import com.wanxsoft.point.R;

import org.apache.cordova.PluginResult;
import org.json.JSONException;
import org.json.JSONObject;

import xu.li.cordova.wechat.Wechat;

public class BrowserActivity extends Activity {

    public static final int CLOSE = 0;
    public static final int GODETAIL = 1;
    public static final int SHARE = 2;

    private String url;

    private WebView webView;
    private ProgressBar mProgress;
    private TextView closeTxt;
    private TextView bTitle;
    private ImageView shareImg;

    private JSONObject h5Data;
    private boolean hasH5Data;
    private int H5DataType;
    private static final int TYPE_DEFAULT = 1;
    private static final int TYPE_SHARE = 2;
    private int shareScene;
    private String webTitle;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            afterFinish();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_browser);
        initBtn();
        initWebView();
        url = getIntent().getStringExtra("url");
        hasH5Data = getIntent().getBooleanExtra("hasH5Data", false);
        H5DataType = TYPE_DEFAULT;
        shareScene = Wechat.SCENE_SESSION;
        webView.loadUrl(url);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (webView.canGoBack()) {
                    webView.goBack();
                } else {
                    if (hasH5Data) {
                        webView.loadUrl("javascript:getH5Data()");
                    } else {
                        handler.sendMessage(new Message());
                    }
                }
        }
        return false;
    }

    @Override
    protected void onPause() {
        overridePendingTransition(android.R.anim.fade_out, android.R.anim.fade_out);
        super.onStop();
    }

    private void showChoiceDialog() {
        View view = LayoutInflater.from(this).inflate(R.layout.view_choice_share, null);
        final Dialog dialog = new Dialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(view);
        dialog.show();
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.share_person:
                        H5DataType = TYPE_SHARE;
                        shareScene = Wechat.SCENE_SESSION;
                        dialog.cancel();
                        if (hasH5Data) {
                            webView.loadUrl("javascript:getH5Data()");
                        } else {
                            shareLink();
                        }
                        break;
                    case R.id.share_pyq:
                        H5DataType = TYPE_SHARE;
                        shareScene = Wechat.SCENE_TIMELINE;
                        dialog.cancel();
                        if (hasH5Data) {
                            webView.loadUrl("javascript:getH5Data()");
                        } else {
                            shareLink();
                        }
                        break;
                    case R.id.btn_close_share:
                        dialog.cancel();
                        break;
                }
            }
        };
        view.findViewById(R.id.share_person).setOnClickListener(listener);
        view.findViewById(R.id.share_pyq).setOnClickListener(listener);
        view.findViewById(R.id.btn_close_share).setOnClickListener(listener);
        Window window = dialog.getWindow();
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        params.gravity = Gravity.BOTTOM;
        window.setAttributes(params);
    }

    private void shareLink() {
        try {
            JSONObject media = new JSONObject();
            media.put("type", 7);
            media.put("webpageUrl", webView.getUrl());
            JSONObject message = new JSONObject();
            message.put("title",webTitle);
            message.put("description",webTitle);
            message.put("media", media);
            JSONObject shareData = new JSONObject();
            shareData.put("message", message);
            shareData.put("type", SHARE);
            shareData.put("scene", shareScene);
            keepCallResult(shareData.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    private void initWebView() {
        webView = (WebView) findViewById(R.id.borwser_wv);
        mProgress = (ProgressBar) findViewById(R.id.dtborwser_pb_progress);
        initWebSettings();
        webView.addJavascriptInterface(this, "DTBrowser");
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress >= 100) {
                    mProgress.setVisibility(View.GONE);
                    closeTxt.setVisibility(webView.canGoBack() ? View.VISIBLE : View.GONE);
                } else {
                    mProgress.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                webTitle = title;
                bTitle.setText(webTitle);
            }
        });
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                webView.loadUrl(url);
                return true;
            }
        });
    }

    private void resultNotFinish(String h5Data) {
        keepCallResult(h5Data);
    }

    private void keepCallResult(String jsonObj) {
        PluginResult result = new PluginResult(PluginResult.Status.OK, jsonObj);
        result.setKeepCallback(true);
        DTBrowser.callback.sendPluginResult(result);
    }

    private void initWebSettings() {
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.getSettings().setDefaultTextEncodingName("UTF-8");
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.getSettings().setBuiltInZoomControls(false);
        webView.getSettings().setSupportMultipleWindows(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setSupportZoom(false);
        webView.getSettings().setPluginState(WebSettings.PluginState.ON);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setLoadsImagesAutomatically(true);
    }

    private void initBtn() {
        closeTxt = (TextView) findViewById(R.id.browser_close);
        shareImg = (ImageView) findViewById(R.id.browser_share);
        bTitle = (TextView) findViewById(R.id.browser_title);

        closeTxt.setVisibility(View.GONE);
        closeTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (hasH5Data) {
                    webView.loadUrl("javascript:getH5Data()");
                } else {
                    handler.sendMessage(new Message());
                }
            }
        });

        shareImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showChoiceDialog();
            }
        });

        findViewById(R.id.browser_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goBack();
            }
        });
    }

    private void goBack() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            if (hasH5Data) {
                webView.loadUrl("javascript:getH5Data()");
            } else {
                afterFinish();
            }
        }
    }

    private void afterFinish() {
        Intent it = getIntent();
        if (hasH5Data) {
            JSONObject jo = new JSONObject();
            try {
                jo.put("h5Data", h5Data);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            it.putExtra("jsonObj", jo.toString());
        }
        setResult(CLOSE, it);
        finish();
    }

    @JavascriptInterface
    public void goPage(String obj) {
        Intent it = getIntent();
        it.putExtra("jsonObj", obj);
        setResult(GODETAIL, it);
        finish();
    }

    @JavascriptInterface
    public void setH5Data(String h5Data) {
        try {
            this.h5Data = new JSONObject(h5Data).getJSONObject("shareData");
            switch (H5DataType) {
                case TYPE_DEFAULT:
                    handler.sendMessage(new Message());
                    break;
                case TYPE_SHARE:
                    this.h5Data.put("type", SHARE);
                    this.h5Data.put("scene", shareScene);
                    resultNotFinish(this.h5Data.toString());
                    H5DataType = TYPE_DEFAULT;
                    break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
